package com.xuan.xuanhttplibrary.okhttp;


import com.sk.weichat.BuildConfig;
import com.umeng.commonsdk.debug.E;
import com.xuan.xuanhttplibrary.okhttp.builder.GetBuilder;
import com.xuan.xuanhttplibrary.okhttp.builder.PostBuilder;
import com.xuan.xuanhttplibrary.okhttp.logger.JsonUtil;
import com.xuan.xuanhttplibrary.okhttp.logger.Logutil;


import okhttp3.OkHttpClient;

import okhttp3.logging.HttpLoggingInterceptor;

/**
 * @author liuxan
 * @time 2017/3/29 23:36
 * @des
 */

public class HttpUtils {

    public static String TAG = "HTTP";

    private static HttpUtils instance = new HttpUtils();

    private HttpUtils() {
    }

    public static HttpUtils getInstance() {
        return instance;
    }

    private OkHttpClient mOkHttpClient;

    private HttpLoggingInterceptor logInterceptor;

    public OkHttpClient getOkHttpClient() {
        if (mOkHttpClient == null) {
            logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            mOkHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(logInterceptor)
                    //.cache(new Cache())
                    // .connectTimeout(15, TimeUnit.SECONDS)
                    //.readTimeout(15, TimeUnit.SECONDS)
                    //.writeTimeout(15, TimeUnit.SECONDS)
                    //.retryOnConnectionFailure(false) //取消自动重连
                    // .addNetworkInterceptor(new StethoInterceptor())
                    .build();
        }
        return mOkHttpClient;
    }

    public static PostBuilder post() {
        return new PostBuilder();
    }

    public static GetBuilder get() {
        return new GetBuilder();
    }

    private static class HttpLogger implements HttpLoggingInterceptor.Logger {
        private StringBuilder mMessage = new StringBuilder();

        static {
            //初始化logger
            Logutil.init(BuildConfig.DEBUG, BuildConfig.NET_LOG_TAG);
        }

        @Override
        public void log(String message) {
            try{
                // 请求或者响应开始
                if (message.startsWith("--> POST")) {
                    mMessage.setLength(0);
                }
                // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
                if ((message.startsWith("{") && message.endsWith("}"))
                        || (message.startsWith("[") && message.endsWith("]"))) {
                    message = JsonUtil.formatJson(message);
                }
                mMessage.append(message.concat("\n"));
                // 请求或者响应结束，打印整条日志
                if (message.startsWith("<-- END HTTP")) {
                    Logutil.e(mMessage.toString());
                    mMessage.setLength(0);
                }
            }catch (Exception e){

            }

        }
    }
}
